<?php

namespace App\Console\Commands;

use App\Library\TencentHandle;
use App\Models\Admin\TencentTemp;
use Illuminate\Console\Command;

class Swoole extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'javascript:swoole';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $serv = new \swoole_server("0.0.0.0", 9501);
        $serv->set(array(
            'worker_num' => 3, //一般设置为服务器CPU数的1-4倍
            'daemonize' => 1, //以守护进程执行
            'max_request' => 10000,
            'dispatch_mode' => 2,
//            'task_worker_num' => 16, //task进程的数量
//            "task_ipc_mode " => 3, //使用消息队列通信，并设置为争抢模式
            "log_file" => app_path()."/../public/swoole.log", //日志存放目录
        ));
        $serv->on('Receive', array($this, 'onReceive'));
        $serv->on('Start', array($this, 'onStart'));
        // bind callback
//        $serv->on('Task', array($this, 'onTask'));
        $serv->on('Finish', array($this, 'onFinish'));
        $serv->start();
    }

    public function onStart($serv) {
        echo "Start\n";
    }
    public function onReceive(\swoole_server $serv, $fd, $reactor_id, $data) {
        echo "onReceive\n";
        $msg = json_decode($data, true); echo "======".print_r($msg);
        if(!empty($msg["id"])){
            $database = TencentTemp::query()->where("id", $msg["id"])->first();
            if(!empty($database)) {
                $request = request();
                $request->mallData = ["id" => $database->mall_id];
                TencentHandle::getInstance()->handleOrderData([
                    "startTime" => $database->start_time, "endTime" => $database->end_time,
                    "object" => $database
                ]);
            }
        }
    }

//    public function onTask($serv, $task_id, $reactor_id, $data) {
//        echo "onTask\n";
//        //在这里进行脚本执行处理操作.
//        $msg = json_decode($data, true);
//        for ($i = 0; $i < count($msg['taskNum']); $i++) {
//
//        }
//        return $data;
//    }

    public function onFinish($serv, $task_id, $data) {
        //任务完成自动调用
        echo "onFinish\n";
    }
}
